<template>
  <div>
    <Category :scene="scene" />
    <el-card style="margin: 10px 0px">
      <div v-if="scene === 0">
        <el-button
          type="primary"
          icon="Plus"
          size="default"
          :disabled="!categoryStore.c3Id"
          @click="addAttr"
        >
          添加平台属性
        </el-button>
        <el-table :data="attrArr" border style="margin: 10px 0px">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            align="center"
            width="150px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称" align="center">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 5px"
                v-for="(item, index) in row.attrValueList"
                :key="item.id"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300px">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                plain
                icon="Edit"
                @click="updateAttr(row)"
              >
                修改
              </el-button>
              <el-popconfirm
                :title="`你确定要删除${row.attrName}吗？`"
                @confirm="deleteArr(row.id)"
                width="200px"
              >
                <template #reference>
                  <el-button type="danger" plain icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 展示添加/修改属性的结果 -->
      <div v-else>
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请您输入属性名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          :disabled="!attrParams.attrName.trim()"
          type="primary"
          size="default"
          icon="Plus"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button @click="cancel">取消</el-button>
        <el-table
          :data="attrParams.attrValueList"
          border
          style="margin: 10px 0px"
        >
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column align="center" label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc:any)=>{inputArr[$index]=vc}"
                v-if="row.flag"
                @blur="toLook(row, $index)"
                placeholder="请你输入属性值名称"
                v-model="row.valueName"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="属性值操作">
            <template #="{ row, $index }">
              <el-button
                plain
                type="danger"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >
          保存
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import useCategoryStore from '@/store/modules/category'
import { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
const categoryStore = useCategoryStore()
// 存取已有的属性和属性值
const attrArr = ref<Attr[]>([])
// 监听仓库三级分类id
// 定义卡片组件的场景切换 0->table 1->修改/添加
let scene = ref<number>(0)
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
})
// 准备一个数组：将来用于存储对应的组件实例：el-input
let inputArr = ref<any>([])
watch(
  () => categoryStore.c3Id,
  () => {
    // 如果c3Id发生变化，应当清空当前的属性和属性值
    attrArr.value = []
    if (!categoryStore.c3Id) return
    getAttr()
  },
)
// 获取已有的属性值和属性方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    attrArr.value = result.data
  }
}
// 添加属性按钮的回调
const addAttr = () => {
  // 每一次带年纪的时候先清空原本的数据
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3,
  })
  scene.value = 1
}
// 修改属性按钮的回调
const updateAttr = (row: Attr) => {
  scene.value = 1
  // 将已有的属性对象赋值给attrParams对象
  Object.assign(attrParams, row)
}
// 删除某一个已有的属性方法回调
const deleteArr = async (attrId: number) => {
  const result: any = await reqRemoveAttr(attrId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
// 取消按钮的回调
const cancel = () => {
  scene.value = 0
}
// 添加属性值按钮的回调
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    // 控制每一个属性值编辑模式的切换
    flag: true,
  })
  // 获取最后的input组件进行聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
// 保存按钮的回调
const save = async () => {
  attrParams.categoryId = categoryStore.c3Id
  const result = await reqAddOrUpdateAttr(attrParams)
  if (result.code == 200) {
    // 切换场景
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    // 获取全部已有的属性和属性值
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
const toLook = (row: AttrValue, $index: number) => {
  // 非法情况的判断 -> 判断输入框是否为空
  if (row.valueName.trim() == '') {
    attrParams.attrValueList.splice($index, 1)
    // 提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  // 非法情况判断 -> 判断attrValueList是否有重复的属性值
  const repeat = attrParams.attrValueList.find((item) => {
    // 排除自己本身的情况从数组判断
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }

  row.flag = false
}
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  //等待input组件成功渲染之后再获取当前input
  nextTick(() => {
    // element中input组件方法 -> 聚焦当前input
    inputArr.value[$index].focus()
  })
}
// 路由组件销毁时，仓库分类相关数据清空
onBeforeUnmount(() => {
  // 清空仓库
  categoryStore.$reset()
})
</script>

<style scoped>
</style>